#!/bin/bash

echo "🚀 快速修复服务器跨域问题..."

# 进入项目目录
cd /var/www/environmental-consulting

# 1. 创建正确的PM2配置文件
echo "📝 创建PM2配置文件..."
cat > ecosystem.config.cjs << 'EOF'
module.exports = {
  apps: [
    {
      name: 'environmental-api',
      script: 'venv/bin/python',
      args: '-m uvicorn app.main:app --host 0.0.0.0 --port 8001',
      cwd: '/var/www/environmental-consulting/backend',
      env: {
        NODE_ENV: 'production',
        DATABASE_URL: 'sqlite:///./environmental_consulting.db',
        SECRET_KEY: 'gzqhsz-environmental-consulting-super-secret-key-2024-production',
        DEBUG: 'false',
        HOST: '0.0.0.0',
        PORT: '8001',
        FRONTEND_URL: 'http://121.37.182.125',
        PYTHONPATH: '/var/www/environmental-consulting/backend'
      },
      instances: 1,
      exec_mode: 'fork',
      watch: false,
      max_memory_restart: '1G',
      autorestart: true,
      error_file: '/var/www/environmental-consulting/logs/api-error.log',
      out_file: '/var/www/environmental-consulting/logs/api-out.log',
      log_file: '/var/www/environmental-consulting/logs/api-combined.log',
      time: true
    }
  ]
};
EOF

# 2. 更新后端环境变量
echo "⚙️ 更新后端环境变量..."
cd backend
cat > .env << 'EOF'
# 生产环境配置
DATABASE_URL=sqlite:///./environmental_consulting.db

# JWT配置
SECRET_KEY=gzqhsz-environmental-consulting-super-secret-key-2024-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# 应用配置
DEBUG=false

# 服务器配置
HOST=0.0.0.0
PORT=8001

# 前端URL（用于CORS）
FRONTEND_URL=https://gzqhst.com
EOF

cd ..

# 3. 创建日志目录
mkdir -p logs

# 4. 停止现有服务并启动新服务
echo "🔄 重启服务..."
pm2 delete all 2>/dev/null || true
pm2 start ecosystem.config.cjs
pm2 save

# 5. 检查服务状态
echo "✅ 检查服务状态..."
sleep 3
pm2 status
echo ""
pm2 logs environmental-api --lines 10

echo ""
echo "🎉 修复完成！"
echo "🌐 前端地址: http://121.37.182.125"
echo "📚 API文档: http://121.37.182.125/docs"
echo "💚 测试命令: curl http://121.37.182.125/api/health"
